home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlsyn.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  21.1 KB  |  556 lines

  1. NAME
  2.        perlsyn - Perl syntax
  3.  
  4. DESCRIPTION
  5.        A Perl script consists of a sequence of declarations and
  6.        statements.  The only things that need to be declared in
  7.        Perl are report formats and subroutines.  See the sections
  8.        below for more information on those declarations.  All
  9.        uninitialized user-created objects are assumed to start
  10.        with a null or 0 value until they are defined by some
  11.        explicit operation such as assignment.  (Though you can
  12.        get warnings about the use of undefined values if you
  13.        like.)  The sequence of statements is executed just once,
  14.        unlike in sed and awk scripts, where the sequence of
  15.        statements is executed for each input line.  While this
  16.        means that you must explicitly loop over the lines of your
  17.        input file (or files), it also means you have much more
  18.        control over which files and which lines you look at.
  19.        (Actually, I'm lying--it is possible to do an implicit
  20.        loop with either the -n or -p switch.  It's just not the
  21.        mandatory default like it is in sed and awk.)
  22.  
  23.        Declarations
  24.  
  25.        Perl is, for the most part, a free-form language.  (The
  26.        only exception to this is format declarations, for obvious
  27.        reasons.) Comments are indicated by the "#" character, and
  28.        extend to the end of the line.  If you attempt to use /*
  29.        */ C-style comments, it will be interpreted either as
  30.        division or pattern matching, depending on the context,
  31.        and C++ // comments just look like a null regular
  32.        expression, so don't do that.
  33.  
  34.        A declaration can be put anywhere a statement can, but has
  35.        no effect on the execution of the primary sequence of
  36.        statements--declarations all take effect at compile time.
  37.        Typically all the declarations are put at the beginning or
  38.        the end of the script.  However, if you're using
  39.        lexically-scoped private variables created with my(),
  40.        you'll have to make sure your format or subroutine
  41.        definition is within the same block scope as the my if you
  42.        expect to to be able to access those private variables.
  43.  
  44.        Declaring a subroutine allows a subroutine name to be used
  45.        as if it were a list operator from that point forward in
  46.        the program.  You can declare a subroutine (prototyped to
  47.        take one scalar parameter) without defining it by saying
  48.        just:
  49.  
  50.            sub myname ($);
  51.            $me = myname $0             or die "can't get myname";
  52.  
  53.        Note that it functions as a list operator though, not as a
  54.        unary operator, so be careful to use or instead of ||
  55.        there.
  56.  
  57.        Subroutines declarations can also be loaded up with the
  58.        require statement or both loaded and imported into your
  59.        namespace with a use statement.  See the perlmod manpage
  60.        for details on this.
  61.  
  62.        A statement sequence may contain declarations of
  63.        lexically-scoped variables, but apart from declaring a
  64.        variable name, the declaration acts like an ordinary
  65.        statement, and is elaborated within the sequence of
  66.        statements as if it were an ordinary statement.  That
  67.        means it actually has both compile-time and run-time
  68.        effects.
  69.  
  70.        Simple statements
  71.  
  72.        The only kind of simple statement is an expression
  73.        evaluated for its side effects.  Every simple statement
  74.        must be terminated with a semicolon, unless it is the
  75.        final statement in a block, in which case the semicolon is
  76.        optional.  (A semicolon is still encouraged there if the
  77.        block takes up more than one line, since you may
  78.        eventually add another line.)  Note that there are some
  79.        operators like eval {} and do {} that look like compound
  80.        statements, but aren't (they're just TERMs in an
  81.        expression), and thus need an explicit termination if used
  82.        as the last item in a statement.
  83.  
  84.        Any simple statement may optionally be followed by a
  85.        SINGLE modifier, just before the terminating semicolon (or
  86.        block ending).  The possible modifiers are:
  87.  
  88.            if EXPR
  89.            unless EXPR
  90.            while EXPR
  91.            until EXPR
  92.  
  93.        The if and unless modifiers have the expected semantics,
  94.        presuming you're a speaker of English.  The while and
  95.        until modifiers also have the usual "while loop" semantics
  96.        (conditional evaluated first), except when applied to a
  97.        do-BLOCK (or to the now-deprecated do-SUBROUTINE
  98.        statement), in which case the block executes once before
  99.        the conditional is evaluated.  This is so that you can
  100.        write loops like:
  101.  
  102.            do {
  103.                $line = <STDIN>;
  104.                ...
  105.            } until $line  eq ".\n";
  106.  
  107.        See the do entry in the perlfunc manpage.  Note also that
  108.        the loop control statements described later will NOT work
  109.        in this construct, since modifiers don't take loop labels.
  110.        Sorry.  You can always wrap another block around it to do
  111.        that sort of thing.
  112.  
  113.        Compound statements
  114.  
  115.        In Perl, a sequence of statements that defines a scope is
  116.        called a block.  Sometimes a block is delimited by the
  117.        file containing it (in the case of a required file, or the
  118.        program as a whole), and sometimes a block is delimited by
  119.        the extent of a string (in the case of an eval).
  120.  
  121.        But generally, a block is delimited by curly brackets,
  122.        also known as braces.  We will call this syntactic
  123.        construct a BLOCK.
  124.  
  125.        The following compound statements may be used to control
  126.        flow:
  127.  
  128.            if (EXPR) BLOCK
  129.            if (EXPR) BLOCK else BLOCK
  130.            if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  131.            LABEL while (EXPR) BLOCK
  132.            LABEL while (EXPR) BLOCK continue BLOCK
  133.            LABEL for (EXPR; EXPR; EXPR) BLOCK
  134.            LABEL foreach VAR (LIST) BLOCK
  135.            LABEL BLOCK continue BLOCK
  136.  
  137.        Note that, unlike C and Pascal, these are defined in terms
  138.        of BLOCKs, not statements.  This means that the curly
  139.        brackets are required--no dangling statements allowed.  If
  140.        you want to write conditionals without curly brackets
  141.        there are several other ways to do it.  The following all
  142.        do the same thing:
  143.  
  144.            if (!open(FOO)) { die "Can't open $FOO: $!"; }
  145.            die "Can't open $FOO: $!" unless open(FOO);
  146.            open(FOO) or die "Can't open $FOO: $!";     # FOO or bust!
  147.            open(FOO) ? 'hi mom' : die "Can't open $FOO: $!";
  148.                                # a bit exotic, that last one
  149.  
  150.        The if statement is straightforward.  Since BLOCKs are
  151.        always bounded by curly brackets, there is never any
  152.        ambiguity about which if an else goes with.  If you use
  153.        unless in place of if, the sense of the test is reversed.
  154.  
  155.        The while statement executes the block as long as the
  156.        expression is true (does not evaluate to the null string
  157.        or 0 or "0").  The LABEL is optional, and if present,
  158.        consists of an identifier followed by a colon.  The LABEL
  159.        identifies the loop for the loop control statements next,
  160.        last, and redo.  If the LABEL is omitted, the loop control
  161.        statement refers to the innermost enclosing loop.  This
  162.        may include dynamically looking back your call-stack at
  163.        run time to find the LABEL.  Such desperate behavior
  164.        triggers a warning if you use the -w flag.
  165.  
  166.        If there is a continue BLOCK, it is always executed just
  167.        before the conditional is about to be evaluated again,
  168.        just like the third part of a for loop in C.  Thus it can
  169.        be used to increment a loop variable, even when the loop
  170.        has been continued via the next statement (which is
  171.        similar to the C continue statement).
  172.  
  173.        Loop Control
  174.  
  175.        The next command is like the continue statement in C; it
  176.        starts the next iteration of the loop:
  177.  
  178.            LINE: while (<STDIN>) {
  179.                next LINE if /^#/;      # discard comments
  180.                ...
  181.            }
  182.  
  183.        The last command is like the break statement in C (as used
  184.        in loops); it immediately exits the loop in question.  The
  185.        continue block, if any, is not executed:
  186.  
  187.            LINE: while (<STDIN>) {
  188.                last LINE if /^$/;      # exit when done with header
  189.                ...
  190.            }
  191.  
  192.        The redo command restarts the loop block without
  193.        evaluating the conditional again.  The continue block, if
  194.        any, is not executed.  This command is normally used by
  195.        programs that want to lie to themselves about what was
  196.        just input.
  197.  
  198.        For example, when processing a file like /etc/termcap.  If
  199.        your input lines might end in backslashes to indicate
  200.        continuation, you want to skip ahead and get the next
  201.        record.
  202.  
  203.            while (<>) {
  204.                chomp;
  205.                if (s/\\$//) {
  206.                    $_ .= <>;
  207.                    redo unless eof();
  208.                }
  209.                # now process $_
  210.            }
  211.  
  212.        which is Perl short-hand for the more explicitly written
  213.        version:
  214.  
  215.  
  216.  
  217.            LINE: while ($line = <ARGV>) {
  218.                chomp($line);
  219.                if ($line =~ s/\\$//) {
  220.                    $line .= <ARGV>;
  221.                    redo LINE unless eof(); # not eof(ARGV)!
  222.                }
  223.                # now process $line
  224.            }
  225.  
  226.        Or here's a a simpleminded Pascal comment stripper
  227.        (warning: assumes no { or } in strings)
  228.  
  229.            LINE: while (<STDIN>) {
  230.                while (s|({.*}.*){.*}|$1 |) {}
  231.                s|{.*}| |;
  232.                if (s|{.*| |) {
  233.                    $front = $_;
  234.                    while (<STDIN>) {
  235.                        if (/}/) {      # end of comment?
  236.                            s|^|$front{|;
  237.                            redo LINE;
  238.                        }
  239.                    }
  240.                }
  241.                print;
  242.            }
  243.  
  244.        Note that if there were a continue block on the above
  245.        code, it would get executed even on discarded lines.
  246.  
  247.        If the word while is replaced by the word until, the sense
  248.        of the test is reversed, but the conditional is still
  249.        tested before the first iteration.
  250.  
  251.        In either the if or the while statement, you may replace
  252.        "(EXPR)" with a BLOCK, and the conditional is true if the
  253.        value of the last statement in that block is true.  While
  254.        this "feature" continues to work in version 5, it has been
  255.        deprecated, so please change any occurrences of "if BLOCK"
  256.        to "if (do BLOCK)".
  257.  
  258.        For Loops
  259.  
  260.        Perl's C-style for loop works exactly like the
  261.        corresponding while loop; that means that this:
  262.  
  263.            for ($i = 1; $i < 10; $i++) {
  264.                ...
  265.            }
  266.  
  267.        is the same as this:
  268.  
  269.  
  270.  
  271.            $i = 1;
  272.            while ($i < 10) {
  273.                ...
  274.            } continue {
  275.                $i++;
  276.            }
  277.  
  278.        Besides the normal array index looping, for can lend
  279.        itself to many other interesting applications.  Here's one
  280.        that avoids the problem you get into if you explicitly
  281.        test for end-of-file on an interactive file descriptor
  282.        causing your program to appear to hang.
  283.  
  284.            $on_a_tty = -t STDIN && -t STDOUT;
  285.            sub prompt { print "yes? " if $on_a_tty }
  286.            for ( prompt(); <STDIN>; prompt() ) {
  287.                # do something
  288.            }
  289.  
  290.  
  291.        Foreach Loops
  292.  
  293.        The foreach loop iterates over a normal list value and
  294.        sets the variable VAR to be each element of the list in
  295.        turn.  The variable is implicitly local to the loop and
  296.        regains its former value upon exiting the loop.  If the
  297.        variable was previously declared with my, it uses that
  298.        variable instead of the global one, but it's still
  299.        localized to the loop.  This can cause problems if you
  300.        have subroutine or format declarations within that block's
  301.        scope.
  302.  
  303.        The foreach keyword is actually a synonym for the for
  304.        keyword, so you can use foreach for readability or for for
  305.        brevity.  If VAR is omitted, $_ is set to each value.  If
  306.        LIST is an actual array (as opposed to an expression
  307.        returning a list value), you can modify each element of
  308.        the array by modifying VAR inside the loop.  That's
  309.        because the foreach loop index variable is an implicit
  310.        alias for each item in the list that you're looping over.
  311.  
  312.        Examples:
  313.  
  314.            for (@ary) { s/foo/bar/ }
  315.  
  316.            foreach $elem (@elements) {
  317.                $elem *= 2;
  318.            }
  319.  
  320.            for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {
  321.                print $count, "\n"; sleep(1);
  322.            }
  323.  
  324.            for (1..15) { print "Merry Christmas\n"; }
  325.            foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
  326.                print "Item: $item\n";
  327.            }
  328.  
  329.        Here's how a C programmer might code up a particular
  330.        algorithm in Perl:
  331.  
  332.            for ($i = 0; $i < @ary1; $i++) {
  333.                for ($j = 0; $j < @ary2; $j++) {
  334.                    if ($ary1[$i] > $ary2[$j]) {
  335.                        last; # can't go to outer :-(
  336.                    }
  337.                    $ary1[$i] += $ary2[$j];
  338.                }
  339.                # this is where that last takes me
  340.            }
  341.  
  342.        Whereas here's how a Perl programmer more confortable with
  343.        the idiom might do it:
  344.  
  345.            OUTER: foreach $wid (@ary1) {
  346.            INNER:   foreach $jet (@ary2) {
  347.                        next OUTER if $wid > $jet;
  348.                        $wid += $jet;
  349.                     }
  350.                  }
  351.  
  352.        See how much easier this is?  It's cleaner, safer, and
  353.        faster.  It's cleaner because it's less noisy.  It's safer
  354.        because if code gets added between the inner and outer
  355.        loops later on, the new code won't be accidentally
  356.        executed, the next explicitly iterates the other loop
  357.        rather than merely terminating the inner one.  And it's
  358.        faster because Perl executes a foreach statement more
  359.        rapidly than it would the equivalent for loop.
  360.  
  361.        Basic BLOCKs and Switch Statements
  362.  
  363.        A BLOCK by itself (labeled or not) is semantically
  364.        equivalent to a loop that executes once.  Thus you can use
  365.        any of the loop control statements in it to leave or
  366.        restart the block.  (Note that this is NOT true in eval{},
  367.        sub{}, or contrary to popular belief do{} blocks, which do
  368.        NOT count as loops.)  The continue block is optional.
  369.  
  370.        The BLOCK construct is particularly nice for doing case
  371.        structures.
  372.  
  373.            SWITCH: {
  374.                if (/^abc/) { $abc = 1; last SWITCH; }
  375.                if (/^def/) { $def = 1; last SWITCH; }
  376.                if (/^xyz/) { $xyz = 1; last SWITCH; }
  377.                $nothing = 1;
  378.            }
  379.        There is no official switch statement in Perl, because
  380.        there are already several ways to write the equivalent.
  381.        In addition to the above, you could write
  382.  
  383.            SWITCH: {
  384.                $abc = 1, last SWITCH  if /^abc/;
  385.                $def = 1, last SWITCH  if /^def/;
  386.                $xyz = 1, last SWITCH  if /^xyz/;
  387.                $nothing = 1;
  388.            }
  389.  
  390.        (That's actually not as strange as it looks once you
  391.        realize that you can use loop control "operators" within
  392.        an expression,  That's just the normal C comma operator.)
  393.  
  394.        or
  395.  
  396.            SWITCH: {
  397.                /^abc/ && do { $abc = 1; last SWITCH; };
  398.                /^def/ && do { $def = 1; last SWITCH; };
  399.                /^xyz/ && do { $xyz = 1; last SWITCH; };
  400.                $nothing = 1;
  401.            }
  402.  
  403.        or formatted so it stands out more as a "proper" switch
  404.        statement:
  405.  
  406.            SWITCH: {
  407.                /^abc/      && do {
  408.                                    $abc = 1;
  409.                                    last SWITCH;
  410.                               };
  411.  
  412.                /^def/      && do {
  413.                                    $def = 1;
  414.                                    last SWITCH;
  415.                               };
  416.  
  417.                /^xyz/      && do {
  418.                                    $xyz = 1;
  419.                                    last SWITCH;
  420.                                };
  421.                $nothing = 1;
  422.            }
  423.  
  424.        or
  425.  
  426.            SWITCH: {
  427.                /^abc/ and $abc = 1, last SWITCH;
  428.                /^def/ and $def = 1, last SWITCH;
  429.                /^xyz/ and $xyz = 1, last SWITCH;
  430.                $nothing = 1;
  431.            }
  432.  
  433.        or even, horrors,
  434.  
  435.            if (/^abc/)
  436.                { $abc = 1 }
  437.            elsif (/^def/)
  438.                { $def = 1 }
  439.            elsif (/^xyz/)
  440.                { $xyz = 1 }
  441.            else
  442.                { $nothing = 1 }
  443.  
  444.        A common idiom for a switch statement is to use foreach's
  445.        aliasing to make a temporary assignment to $_ for
  446.        convenient matching:
  447.  
  448.            SWITCH: for ($where) {
  449.                        /In Card Names/     && do { push @flags, '-e'; last; };
  450.                        /Anywhere/          && do { push @flags, '-h'; last; };
  451.                        /In Rulings/        && do {                    last; };
  452.                        die "unknown value for form variable where: `$where'";
  453.                    }
  454.  
  455.        Another interesting approach to a switch statement is
  456.        arrange for a do block to return the proper value:
  457.  
  458.            $amode = do {
  459.                if     ($flag & O_RDONLY) { "r" }
  460.                elsif  ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
  461.                elsif  ($flag & O_RDWR)   {
  462.                    if ($flag & O_CREAT)  { "w+" }
  463.                    else                  { ($flag & O_APPEND) ? "a+" : "r+" }
  464.                }
  465.            };
  466.  
  467.  
  468.        Goto
  469.  
  470.        Although not for the faint of heart, Perl does support a
  471.        goto statement.  A loop's LABEL is not actually a valid
  472.        target for a goto; it's just the name of the loop.  There
  473.        are three forms: goto-LABEL, goto-EXPR, and goto-&NAME.
  474.  
  475.        The goto-LABEL form finds the statement labeled with LABEL
  476.        and resumes execution there.  It may not be used to go
  477.        into any construct that requires initialization, such as a
  478.        subroutine or a foreach loop.  It also can't be used to go
  479.        into a construct that is optimized away.  It can be used
  480.        to go almost anywhere else within the dynamic scope,
  481.        including out of subroutines, but it's usually better to
  482.        use some other construct such as last or die.  The author
  483.        of Perl has never felt the need to use this form of goto
  484.        (in Perl, that is--C is another matter).
  485.  
  486.        The goto-EXPR form expects a label name, whose scope will
  487.        be resolved dynamically.  This allows for computed gotos
  488.        per FORTRAN, but isn't necessarily recommended if you're
  489.        optimizing for maintainability:
  490.  
  491.            goto ("FOO", "BAR", "GLARCH")[$i];
  492.  
  493.        The goto-&NAME form is highly magical, and substitutes a
  494.        call to the named subroutine for the currently running
  495.        subroutine.  This is used by AUTOLOAD() subroutines that
  496.        wish to load another subroutine and then pretend that the
  497.        other subroutine had been called in the first place
  498.        (except that any modifications to @_ in the current
  499.        subroutine are propagated to the other subroutine.)  After
  500.        the goto, not even caller() will be able to tell that this
  501.        routine was called first.
  502.  
  503.        In almost all cases like this, it's usually a far, far
  504.        better idea to use the structured control flow mechanisms
  505.        of next, last, or redo instead of resorting to a goto.
  506.        For certain applications, the catch and throw pair of
  507.        eval{} and die() for exception processing can also be a
  508.        prudent approach.
  509.  
  510.        PODs: Embedded Documentation
  511.  
  512.        Perl has a mechanism for intermixing documentation with
  513.        source code.  While it's expecting the beginning of a new
  514.        statement, if the compiler encounters a line that begins
  515.        with an equal sign and a word, like this
  516.  
  517.            =head1 Here There Be Pods!
  518.  
  519.        Then that text and all remaining text up through and
  520.        including a line beginning with =cut will be ignored.  The
  521.        format of the intervening text is described in the perlpod
  522.        manpage.
  523.  
  524.        This allows you to intermix your source code and your
  525.        documentation text freely, as in
  526.  
  527.            =item snazzle($)
  528.  
  529.            The snazzle() function will behave in the most spectacular
  530.            form that you can possibly imagine, not even excepting
  531.            cybernetic pyrotechnics.
  532.  
  533.            =cut back to the compiler, nuff of this pod stuff!
  534.  
  535.            sub snazzle($) {
  536.                my $thingie = shift;
  537.                .........
  538.            }
  539.  
  540.        Note that pod translators should only look at paragraphs
  541.        beginning with a pod diretive (it makes parsing easier),
  542.        whereas the compiler actually knows to look for pod
  543.        escapes even in the middle of a paragraph.  This means
  544.        that the following secret stuff will be ignored by both
  545.        the compiler and the translators.
  546.  
  547.            $a=3;
  548.            =secret stuff
  549.             warn "Neither POD nor CODE!?"
  550.            =cut back
  551.            print "got $a\n";
  552.  
  553.        You probably shouldn't rely upon the warn() being podded
  554.        out forever.  Not all pod translators are well-behaved in
  555.        this regard, and perhaps the compiler will become pickier.
  556.